package com.audi.activity;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.R;



import com.audi.BaseActivity;
import com.audi.adapter.ListDeviceCardAdapterBottom;
import com.audi.adapter.ListDeviceCardAdapterTop;
import com.audi.adapter.PlaceCardDevicesAdapter;
import com.audi.adapter.RootAccessAdapter;
import com.audi.adapter.SQLiteAsusNewHelper;
import com.audi.adapter.SceneAdapter;
import com.audi.dslv.DragSortController;
import com.audi.dslv.DragSortListView;
import com.audi.dslv.DragSortListView.DropListener;
import com.audi.dto.DeviceItem;
import com.audi.dto.PlaceItem;
import com.audi.dto.SceneItem;
import com.audi.handler.MemberHandlerAction;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.view.BaseDeviceDialog;
import com.audi.view.BaseSceneDialog;
import com.audi.view.DeviceUpdatePhoto;

@SuppressLint("Registered")
public class NewActivityPlaceInfo extends BaseActivity implements
		OnClickListener, OnMenuItemClickListener {
	public ImageButton btnDelete;
	@SuppressWarnings("unused")
	private ImageView mBtnEditNamePlace, mIconPlace;
	private DeviceUpdatePhoto mDeviceUpdatePhotoHomeControl;
	private SendMessage sendMessage;
	private TextView btnTabDevice, btnTabScene, btnTabInfo;
	private TextView DateCreated, numOfDevice, typeOfPlace, placeName,
			placeNameActionBar;
	private GridView grvListDevice;
	private DragSortController mController;
	private LinearLayout mLnlTabScene, mLnlPrivacy;
	private RelativeLayout mLnlTabInfo;
	private ImageView btnAddInDeviceTabBar, btnMenuInDeviceTabBar;
	private ImageView mbtnAddScene;
	public PlaceCardDevicesAdapter mPlaceCardDevicesAdapter;
	private ArrayList<DeviceItem> mListDeviceInRootAccess;

	private DeviceUpdatePhoto deviceUpdatePhoto;
	private PlaceItem mPlaceItem;
	private PopupMenu mPopMenuPlaceInfo;

	private SceneAdapter mSceneAdapter;
	private DragSortListView mSceneListView;
	private ArrayList<SceneItem> mListSceneInRootAccess;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		mPlaceItem = (PlaceItem) intent.getExtras().getSerializable("item");
		mListDeviceInRootAccess =new ArrayList<DeviceItem>();
		mListSceneInRootAccess =new ArrayList<SceneItem>();
		mPlaceItem.setDateCreated("04, Agu. 2014");
		setContentView(R.layout.new_activity_info_place);
		initActionBar(R.layout.action_bar_place_card_info);
		setDisableDrawer();
		sendMessage = new SendMessage();
		mDeviceUpdatePhotoHomeControl = new DeviceUpdatePhoto(this);
		initView();
		initData();
		onClickTabInfo();
		initListener();
	}

	public DropListener onDrop = new DropListener() {
		public void drop(int from, int to) {
			if (from != to) {
				SceneItem sceneItem = (SceneItem) mListSceneInRootAccess.get(from);
				mListSceneInRootAccess.remove(from);
				mListSceneInRootAccess.add(to, sceneItem);
				mSceneAdapter.notifyDataSetChanged();
			}
		}
	};

	protected void onClickDeviceInfo() {
		// TODO Auto-generated method stub
		btnMenuInDeviceTabBar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showPopupMenuPlaceInfo();
			}
		});
		btnAddInDeviceTabBar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// finish();
			}
		});
		placeNameActionBar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
	}
	private void onClickScene()
	{
		mbtnAddScene.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				addScene();
				
			}
		});
	}
	private void addScene()
	{
		
		BaseSceneDialog addSceneDialog = new BaseSceneDialog(this);
		addSceneDialog.onAddSceneDialog();
	}
	protected void initView() {
		mLnlTabScene = (LinearLayout) findViewById(R.id.lnl_scene);
		mLnlTabInfo = (RelativeLayout) findViewById(R.id.lnl_info_place);
		grvListDevice = (GridView) findViewById(R.id.gridView_listDevice);
		mLnlPrivacy = (LinearLayout) findViewById(R.id.lnl_Privacy);
		btnTabDevice = (TextView) findViewById(R.id.tab_device);
		btnTabScene = (TextView) findViewById(R.id.tab_scene);
		btnTabInfo = (TextView) findViewById(R.id.tab_info);
		mBtnEditNamePlace = (ImageView) findViewById(R.id.btn_edit_placename);

		mIconPlace = (ImageView) findViewById(R.id.img_icon_place_in_PlaceInfo);
		DateCreated = (TextView) findViewById(R.id.txtDate);
		mBtnEditNamePlace = (ImageView) findViewById(R.id.btn_edit_placename);
		numOfDevice = (TextView) findViewById(R.id.txt_numberOfDevice_Show);
		typeOfPlace = (TextView) findViewById(R.id.txtTypeOfplace);
		placeName = (TextView) findViewById(R.id.txt_placeNameInfo);
		placeNameActionBar = (TextView) findViewById(R.id.tv_place_name);
		btnDelete = (ImageButton) findViewById(R.id.btn_recycle);
		mLnlTabScene.setVisibility(View.VISIBLE);
		mLnlTabInfo.setVisibility(View.VISIBLE);
		grvListDevice.setVisibility(View.GONE);
		mSceneListView = (DragSortListView) findViewById(R.id.lv_list_scenes);
		setEnaleTab(1);

		mController = new DragSortController(mSceneListView);
		mController.setDragHandleId(R.id.rlt_drag_scene);
		mController.setRemoveEnabled(false);
		mController.setSortEnabled(true);
		mController.setDragInitMode(2);
		mSceneListView.setFloatViewManager(mController);
		mSceneListView.setOnTouchListener(mController);
		mSceneListView.setDragEnabled(true);
		mSceneListView.setDropListener(onDrop);

	}

	private void showPopupMenuPlaceInfo() {
		mPopMenuPlaceInfo = new PopupMenu(NewActivityPlaceInfo.this,
				btnMenuInDeviceTabBar);
		mPopMenuPlaceInfo.getMenuInflater().inflate(
				R.menu.popup_menu_place_card_device_info,
				mPopMenuPlaceInfo.getMenu());
		mPopMenuPlaceInfo.show();
		mPopMenuPlaceInfo
				.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem index) {
						if (index.getItemId() == R.id.move_device_to) {
							Intent intentDeviceCard = new Intent(
									NewActivityPlaceInfo.this,
									SelectDevicesActivity.class);
							Bundle bundleInfoPlace = new Bundle();
							bundleInfoPlace.putSerializable("placeItem",
									mPlaceItem);
							intentDeviceCard.putExtras(bundleInfoPlace);
							startActivity(intentDeviceCard);
						}
						if (index.getItemId() == R.id.delete_place) {
							// Code delete device.
						}
						return true;
					}
				});
	}

	
	private void initData() {
		placeNameActionBar.setText(mPlaceItem.getPlaceName());
		placeName.setText(mPlaceItem.getPlaceName());
		if (mPlaceItem.getCapabilityType() != 1)
			typeOfPlace.setText("Public");
		else {
			typeOfPlace.setText("Private");
		}
		numOfDevice.setText(mPlaceItem.getDeviceNumber() + "");
		// placeName.setText(mPlaceItem.getPlaceName());
		DateCreated.setText(mPlaceItem.getDateCreated());
	}
	
	private void initListener() {
		btnTabDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				setEnaleTab(1);
			}
		});
		btnTabScene.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setEnaleTab(2);
			}
		});

		btnTabInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setEnaleTab(3);
			}
		});
		mLnlPrivacy.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(getApplicationContext(), "Change privacy",
						Toast.LENGTH_LONG).show();
			}
		});
		
	}

	@Override
	public boolean onMenuItemClick(MenuItem arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onRefreshData() {
		// TODO Auto-generated method stub
		mSceneAdapter.setDataForAdapterScene(mListSceneInRootAccess);
	}

	public void onClickTabInfo() {
		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});
		placeNameActionBar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
	}

	private void setEnaleTab(int index) {
		switch (index) {
		case 1:
			initActionBar(R.layout.action_bar_device_place_card_info);
			placeNameActionBar = (TextView) findViewById(R.id.tv_place_name_2);
			placeNameActionBar.setText(mPlaceItem.getPlaceName());
			btnAddInDeviceTabBar = (ImageView) findViewById(R.id.img_icon_device_on);
			btnMenuInDeviceTabBar = (ImageView) findViewById(R.id.imv_menu_place_info);
			onClickDeviceInfo();
			btnTabDevice.setTextColor(Color.WHITE);
			btnTabDevice.setBackgroundResource(R.drawable.btn_tab_on);
			btnTabScene.setTextColor(Color.BLACK);
			btnTabScene.setBackgroundResource(R.drawable.btn_tab_off);
			btnTabInfo.setTextColor(Color.BLACK);
			btnTabInfo.setBackgroundResource(R.drawable.btn_tab_off);
			mLnlTabScene.setVisibility(View.GONE);
			mLnlTabInfo.setVisibility(View.GONE);
			grvListDevice.setVisibility(View.VISIBLE);
			updateDevice();
			break;
		case 2:
			initActionBar(R.layout.action_bar_scene_place_card_info);
			placeNameActionBar = (TextView) findViewById(R.id.tv_place_name_in_scene);
			placeNameActionBar.setText(mPlaceItem.getPlaceName());
			mbtnAddScene = (ImageView) findViewById(R.id.imv_add_scene);
			onClickScene();
			btnTabDevice.setTextColor(Color.BLACK);
			btnTabDevice.setBackgroundResource(R.drawable.btn_tab_off);
			btnTabScene.setTextColor(Color.WHITE);
			btnTabScene.setBackgroundResource(R.drawable.btn_tab_on);
			btnTabInfo.setTextColor(Color.BLACK);
			btnTabInfo.setBackgroundResource(R.drawable.btn_tab_off);
			mLnlTabScene.setVisibility(View.VISIBLE);
			mLnlTabInfo.setVisibility(View.GONE);
			grvListDevice.setVisibility(View.GONE);
			updateScene();
			onClickTabInfo();
			break;

		case 3:
			initActionBar(R.layout.action_bar_place_card_info);
			placeNameActionBar = (TextView) findViewById(R.id.tv_place_name);
			btnTabInfo.setTextColor(Color.WHITE);
			btnTabInfo.setBackgroundResource(R.drawable.btn_tab_on);
			btnTabScene.setTextColor(Color.BLACK);
			btnTabScene.setBackgroundResource(R.drawable.btn_tab_off);
			btnTabDevice.setTextColor(Color.BLACK);
			btnTabDevice.setBackgroundResource(R.drawable.btn_tab_off);
			grvListDevice.setVisibility(View.GONE);
			mLnlTabScene.setVisibility(View.GONE);
			mLnlTabInfo.setVisibility(View.VISIBLE);
			placeNameActionBar.setText(mPlaceItem.getPlaceName());
			onClickTabInfo();
			break;
		}
	}

	public void loadListScene(ArrayList<SceneItem> listScene) {
		try {
			mListSceneInRootAccess = listScene;
			if (mListSceneInRootAccess != null) {
				if (mSceneAdapter == null) {
					mSceneAdapter = new SceneAdapter(
							this, mListSceneInRootAccess, deviceUpdatePhoto);
					mSceneListView.setAdapter(mSceneAdapter);
				} else {
					mSceneAdapter.setDataForAdapterScene(mListSceneInRootAccess);
				}

			}
		} catch (Exception e) {
			Log.e("load list device", e.toString());
		}
	}


	public void loadListDevice(ArrayList<DeviceItem> listDevice) {
		try {
			mListDeviceInRootAccess = listDevice;
			if (mListDeviceInRootAccess != null) {
			
				if (mPlaceCardDevicesAdapter == null) {
					mPlaceCardDevicesAdapter = new PlaceCardDevicesAdapter(
							this, mListDeviceInRootAccess, deviceUpdatePhoto);
					grvListDevice.setAdapter(mPlaceCardDevicesAdapter);
				} else {
					mPlaceCardDevicesAdapter.setDataForAdapterDevice(mListDeviceInRootAccess);
				}

			} 

		} catch (Exception e) {
			Log.e("load list device", e.toString());
		}
	}

	
	@SuppressLint("HandlerLeak")
	private Handler loadListDeviceHandler = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							@SuppressWarnings("unchecked")
							ArrayList<DeviceItem> result = (ArrayList<DeviceItem>) msg
									.getData()
									.getSerializable(
											String.valueOf(ActionMessage.GET_DEVICE_LIST_BY_PLACE));
							loadListDevice(result);
						}
					} catch (Exception e) {
						Log.e("load list device", e.toString());
					}
				}
			});
		}
	};
	@SuppressLint("HandlerLeak")
	public Handler loadListSceneHandlerRootAccess = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							@SuppressWarnings("unchecked")
							ArrayList<SceneItem> result = (ArrayList<SceneItem>) msg
									.getData()
									.getSerializable(

											String.valueOf(ActionMessage.GET_LIST_SCENE));
							loadListScene(result);
							
						} else {
							// DestroyProgressDialog();

						}
					} catch (Exception e) {
					}
				}
			});
		}
	};
	@Override
	protected void onResume() {
		super.onResume();
		updateDevice();
		updateScene();
	}

	// update data for UI Device.
	private void updateDevice() {
	    
		sendMessage.sendData(ActionMessage.GET_DEVICE_LIST_BY_PLACE, mPlaceItem.getPlaceId(),
				loadListDeviceHandler);

	}
	// update data for UI Scene.
	private void updateScene() {
		sendMessage.sendData(ActionMessage.GET_LIST_SCENE, null,
				loadListSceneHandlerRootAccess);
	}


	public final void renameDeviceFuntion(DeviceItem deviceItem) {
		BaseDeviceDialog renameDevice = new BaseDeviceDialog(this);
		renameDevice.editNameDevice(deviceItem, handlerUpdateDevice);
	}

	// delete device
	public void deleteDeviceFuntion(DeviceItem deviceItem) {
		BaseDeviceDialog RemoveDialog = new BaseDeviceDialog(this);
		RemoveDialog.removeDevice(deviceItem, handlerUpdateDevice);

	}
	// change Photo device
	public void changePhotoDeviceFuntion(DeviceItem deviceItem) {
		mDeviceUpdatePhotoHomeControl.updatePhoto();
	}

	// change place device
	public void changePlaceDeviceFuntion(DeviceItem deviceItem) {
		BaseDeviceDialog changePlaceDialog = new BaseDeviceDialog(this);
		changePlaceDialog
				.showSelectPlaceDialog(deviceItem, handlerUpdateDevice);

	}

	@SuppressLint("HandlerLeak")
	private Handler handlerUpdateDevice = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							// status
							if (msg.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_DEVICE)) > 0) {
								sendMessage.sendData(ActionMessage.getAllDeviceList, null,
										loadListDeviceHandler);
							}

						}
					} catch (Exception e) {
					}
				}
			});
		}
	};
	

	int tempActionResult;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent myIntent = new Intent(this, ActivityReviewImageCrop.class);
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 555) {
			mDeviceUpdatePhotoHomeControl.dimissUpdate();
			Log.d("start crop", "dgfgfdgfdgdf");
			tempActionResult = 0;
		}
		if (resultCode == RESULT_OK) {
			if (requestCode == mDeviceUpdatePhotoHomeControl.cameraCapture) {
				mDeviceUpdatePhotoHomeControl
						.performcrop(mDeviceUpdatePhotoHomeControl.getPicUri());
				Log.d("start crop", "crop crop crop");
				tempActionResult = 1;
			} else if (requestCode == mDeviceUpdatePhotoHomeControl.picCrop) {
				myIntent.putExtra("Req",
						mDeviceUpdatePhotoHomeControl.getstatus());
				this.startActivityForResult(myIntent, 555);

				Log.d("start crop", "reviview=====-''/////");
				tempActionResult = 0;
			}
			if (requestCode == mDeviceUpdatePhotoHomeControl.pickFromFile) {
				tempActionResult = 2;
				mDeviceUpdatePhotoHomeControl.setPicUri(data.getData());
				mDeviceUpdatePhotoHomeControl
						.performcrop(mDeviceUpdatePhotoHomeControl.getPicUri());
				Log.d("start crop", "pick  form file=====- " + tempActionResult);

			}
		} else {
			if (tempActionResult == 1) {
				mDeviceUpdatePhotoHomeControl.camphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
			}
			if (tempActionResult == 2) {
				mDeviceUpdatePhotoHomeControl.picphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
			}
		}
	}

}